"""
FastAPI 应用工厂模块
实现应用初始化、中间件注册和路由加载
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from typing import List, Dict, Any, Optional

from pkg.settings.config import settings


def create_app() -> FastAPI:
    """
    创建并配置FastAPI应用实例
    :return: 配置好的FastAPI应用实例
    """
    # 创建FastAPI应用
    app = FastAPI(
        title=settings.APP_NAME,
        debug=settings.DEBUG,
        docs_url="/api/docs" if settings.DEBUG else None,
        redoc_url="/api/redoc" if settings.DEBUG else None,
    )
    
    # 配置CORS
    setup_cors(app)
    
    # 配置静态文件
    setup_static_files(app)
    
    # 注册中间件
    register_middlewares(app)
    
    # 注册路由
    register_routers(app)
    
    return app


def setup_cors(app: FastAPI) -> None:
    """
    配置CORS中间件
    :param app: FastAPI应用实例
    """
    app.add_middleware(
        CORSMiddleware,
        allow_origins=settings.CORS_ORIGINS,
        allow_methods=settings.CORS_METHODS,
        allow_headers=settings.CORS_HEADERS,
        allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
    )


def setup_static_files(app: FastAPI) -> None:
    """
    配置静态文件服务
    :param app: FastAPI应用实例
    """
    static_dir = Path(settings.BASE_DIR) / "resources" / "static"
    if static_dir.exists():
        app.mount("/static", StaticFiles(directory=str(static_dir)), name="static")


def register_middlewares(app: FastAPI) -> None:
    """
    注册应用中间件
    :param app: FastAPI应用实例
    """
    from pkg.middlewares.middleware import setup_middlewares
    setup_middlewares(app)


def register_routers(app: FastAPI) -> None:
    """
    注册API路由
    :param app: FastAPI应用实例
    """
    from pkg.core.urls import setup_routes
    setup_routes(app)
